package com.java.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.config.exceptioin.YyghException;
import com.java.config.result.ResultCodeEnum;
import com.java.common.helper.JwtHelper;
import com.java.mapper.UserInfoMapper;
import com.java.model.user.Patient;
import com.java.model.user.UserInfo;
import com.java.model.vo.LoginVo;
import com.java.model.vo.UserAuthVo;
import com.java.model.vo.UserInfoQueryVo;
import com.java.service.PatientService;
import com.java.service.UserInfoService;
import com.java.utils.AuthStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {



    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    /**
     * 登录流程
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {

        //得到手机号 和 验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断手机号 或 验证码 是否为空 手机号短信发送申请不了 直接判手机号
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
           throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        UserInfo userInfo = null;
        //在redis中获取验证码 mobileCode ： 1234 假数据
        String mobileCode = redisTemplate.opsForValue().get(phone);
        //判断验证码是否相等
        if(!code.equals(mobileCode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        //绑定手机号 如果 Openid不为空就绑定
        if(!StringUtils.isEmpty(loginVo.getOpenid())){
            //根据openid拿到userinfo
            userInfo = this.getByOpenid(loginVo.getOpenid());
            if(null != userInfo){
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            }else{
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }
        //Openid为空就不绑定
        if(StringUtils.isEmpty(loginVo.getOpenid())){
            //判断是否是第一次登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<UserInfo>();
            wrapper.eq("phone",phone);
            userInfo = userInfoMapper.selectOne(wrapper);
            //如果用户不存在 说明是第一次登录 增加用户数据
            if(null == userInfo){
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                userInfoMapper.insert(userInfo);
            }
        }

        //校验是否被禁用
        if(userInfo.getStatus() == 0){
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //TODO记录登录
        //返回页面显示数据
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        //JWT生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("name", name);
        map.put("token",token);

        return map;
    }

    @Override
    public UserInfo getByOpenid(String openid) {
        QueryWrapper<UserInfo> mapper = new QueryWrapper<>();
        mapper.eq("openid",openid);
        return userInfoMapper.selectOne(mapper);
    }


    //用户认证
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //上传证件用elementui组件上传到阿里容器
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //认证名称
        userInfo.setName(userAuthVo.getName());
        //证件类型
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        //证件编号
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        //证件路径
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        //认证中
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //认证的基本操作
        userInfoMapper.updateById(userInfo);
    }


    //用户审核列表分页条件查询
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {

        String name = userInfoQueryVo.getKeyword();//用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();//认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        //对条件值非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)){
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            wrapper.le("update_time",createTimeEnd);
        }
        IPage<UserInfo> page = userInfoMapper.selectPage(pageParam,wrapper);
        page.getRecords().stream().forEach(item->{
            packageUserInfo(item);
        });
        return page;
    }

    //用户锁定
    @Override
    public void lock(Long userId, Integer status) {
        //status == 0 || status == 1
        if(true){
            UserInfo userInfo = userInfoMapper.selectById(userId);
            userInfo.setStatus(status);
            userInfoMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        UserInfo userInfo =packageUserInfo(userInfoMapper.selectById(userId)) ;
        List<Patient> patientList = patientService.findList(userId);
        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;
    }

    //认证审批
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue() == 2 || authStatus.intValue() == -1){
            UserInfo userInfo = userInfoMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            userInfoMapper.updateById(userInfo);
        }
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatus",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        String statusString = userInfo.getStatus().intValue() == 0?"锁定":"正常";
        userInfo.getParam().put("status",statusString);
        return userInfo;
    }


}
